from rest_framework import serializers
import re
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings

from celery_tasks.email.tasks import send_verify_email
from .models import User, Address
from goods.models import SKU
from . import constants
# 用户注册
class CreateUserSerializer(serializers.ModelSerializer):
    '''
    username	str	是	用户名
    password	str	是	密码
    password2	str	是	确认密码
    sms_code	str	是	短信验证码
    mobile	str	是	手机号
    allow
    {
    "id": 9,
    "username": "python8",
    "mobile": "18512345678",
    }
    '''

    password2 = serializers.CharField(write_only=True, label='校验密码')
    sms_code = serializers.CharField(write_only=True, label='短信验证码')
    allow = serializers.CharField(write_only=True, label='同意协议')
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段
    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'password2', 'sms_code', 'mobile', 'allow', 'token']
        extra_kwargs = {
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 8,
                'error_messages': {
                    'max_length': '密码要8-20位',
                    'min_length': '密码要8-20位',
                }
            },
            'username': {
                'max_length': 20,
                'min_length': 5,
                'error_messages': {
                    'max_length': '用户名要5-20位',
                    'min_length': '用户名要5-20位',
                }
            },

        }
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号不符合规则')
        return value
    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('请先同意协议')
        return value

    def validate(self, attrs):
        password = attrs['password']
        password2 = attrs['password2']
        if password != password2:
            raise serializers.ValidationError('密码不一致')
        mobile = attrs['mobile']
        sms_code = attrs['sms_code']
        redis_conn = get_redis_connection('verify_codes')
        real_sms = redis_conn.get('sms_%s' % mobile)
        if real_sms is None:
            raise serializers.ValidationError('验证码已过期')
        if real_sms.decode() != sms_code:
            raise serializers.ValidationError('手机验证码错误')
        return attrs

    def create(self, validated_data):
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user

# 用户个人信息展示
class UserDetailSerializer(serializers.ModelSerializer):
    '''
    用户个人信息展示
    id username mobile email email_active
    '''

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']

# 添加邮箱信息
class EmailSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwargs = {
            'email': {
                'required': 'True'
            }
        }
    def update(self, instance, validated_data):

        email = validated_data['email']
        instance.email = email
        instance.save()
        # 生成邮箱链接
        verify_email_url = instance.generate_verify_email_url()
        # 发送邮箱链接
        send_verify_email.delay(email, verify_email_url)
        return instance

# 用户地址新增与修改
class UserAddressSerializer(serializers.ModelSerializer):
    '''用户地址序列化器'''
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ['user', 'is_deleted', 'create_time', 'update_time']

    def validate_mobile(self, value):
        '''验证手机号'''
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        '''保存'''
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)

# 用户地址修改标题
class AddressTitleSerializer(serializers.ModelSerializer):
    '''地址标题'''
    class Meta:
        model = Address
        fields = ['title']

# 用户浏览记录添加
class AddUserBrowsingHistorySerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(label='商品sku编号', min_value=1)
    def validate_sku_id(self, value):
        '''检查sku_id'''
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('sku_id不存在')
        return value

    def create(self, validated_data):

        user_id = self.context['request'].user.id
        sku_id = validated_data['sku_id']

        redis_coon = get_redis_connection('history')
        pl = redis_coon.pipeline()

        pl.lrem("history_%s" % user_id, 0, sku_id)
        pl.lpush("history_%s" % user_id, sku_id)
        pl.ltrim("history_%s" % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT-1)
        pl.execute()
        return validated_data

































